<?php
namespace api\modules\sms\impcommon;
use api\modules\sms\icommon\Isms;
use api\modules\sms\models\WhoSmsLog;
use api\helpers\SmsHelper;


/**
 * User: ziwen
 * Date: 2016/1/28 11:42
 * File: splio.php
 * Desc: ""
 */
class nexmo implements Isms{
    public static $instance;

    private function __construct(){
    }

    public static function getInstance()
    {
        if(self::$instance){
            return self::$instance;
        }else{
            self::$instance = new self();
            return self::$instance;
        }
    }

    //https://rest.nexmo.com/sms/json?api_key=xxxxxxxx&api_secret=xxxxxxxx&to=xxxxxxxxxxxx&from=NexmoWorks&text=hello+from+Nexmo
    private static $api_key = 'd5eb68d8';
    private static $api_secret = '329df2a8';

    private static $apiUrl = 'https://rest.nexmo.com/sms/json?';

    /**
     * @desc 发送信息
     */
    public function sendMsg(array $sendData){
        $url = $this->buildUrl($sendData);
        $status = 0;
        $ret = self::sendHttpsUrl($url);
        if($ret['httpcode'] == 200){
            //传入的是一个json
            $response = self::processRet($ret['return_message']);
            if($response['status'] == 'ok' && $response['code'] == 0 ){
                $status = 1;
            }
        }

        $parmars['api_key'] = self::getApikey();
        $parmars['api_secret'] = self::getApiSecret();
        $parmars['from'] = $sendData['from'];
        $parmars['text'] = $sendData['text'];
        $parmars['to'] = $sendData['to'];
        $parmars['type'] = $sendData['type'];

        $data = array(
            'mobile'=>$sendData['to'],
            'query_url'=>$url,
            'log_time'=>time(),
            'status'=>$status,
            'return_message'=>$ret['return_message'],
            'channel'=>2,
            'type'=>0,
            'content'=>$sendData['verify_code'].'',
            'source_id'=>$sendData['source_id']
        );
        $smsLogModel = new WhoSmsLog();
        $smsLogModel->setAttributes($data);
        if(!$smsLogModel->save()){
            SmsHelper::pr($smsLogModel->getErrors());
        }
        return array('status'=>$status,'smsid'=>$smsLogModel->attributes['id']);
    }


    /**
     * @param $url
     * @return array
     */
    private static function sendHttpsUrl($url){
        $timeOut = 60;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        //不进行ssl的认证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ret = curl_exec($ch);
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);

        $returnArr = array('httpcode'=>$httpCode,'return_message'=>$ret);
        return $returnArr;
    }

    //获取api_key
    private static function getApikey(){
        self::$api_key = self::$api_key;
        return self::$api_key;
    }

    //获取api_secretapi_secret
    private static function getApiSecret(){
        self::$api_secret = self::$api_secret;
        return self::$api_secret;
    }

    private static function getApiUrl(){
        return self::$apiUrl;
    }

    /**
     * @desc 构造发送短信的参数
     */
    private function buildUrl($data){
        $dataList = array();
        $dataList['api_key'] = self::getApikey();
        $dataList['api_secret'] = self::getApiSecret();
        $dataList['from'] = $data['from'];
        $dataList['text'] = $data['text'];
        $dataList['to'] = $data['to'];
        $dataList['type'] = $data['type'];

        $queryUrl = http_build_query($dataList);
        $this->requestUrl = self::getApiUrl().$queryUrl;
        return $this->requestUrl;
    }

    /**
     * @param $response
     * @desc 解析发送后，返回的结果
     */
    private static function processRet($jsonData){
        $ret = array();
        if($jsonData){
            $response = json_decode($jsonData,true);
            if(isset($response['message-count']) && $response['message-count']==1){
                $messages = $response['messages'];
                $message = current($messages);
                if($message['status']==0){
                    $ret = array(
                        'status'=>'ok',
                        'code'=>0,
                        'message'=>'success'
                    );
                }else{
                    $ret = array(
                        'status'=>'error',
                        'code'=>$message['status'],
                        'message'=>$message['error-text']
                    );
                }
            }
        }
        return $ret;
    }
}
